import sys
import os
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, 
                             QHBoxLayout, QLabel, QLineEdit, QPushButton, 
                             QTableWidget, QTableWidgetItem, QMessageBox,
                             QTabWidget, QComboBox, QHeaderView, QFrame, 
                             QGroupBox, QFormLayout, QSizePolicy, QDateEdit)
from PyQt5.QtCore import Qt, QSize, QDate
from PyQt5.QtGui import QFont, QColor, QPalette, QIcon
import sqlite3
from datetime import datetime
import pandas as pd
from openpyxl import Workbook
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas

class DevExpressStyle:
    @staticmethod
    def apply_style(app):
        app.setStyle("Fusion")
        
        palette = app.palette()
        palette.setColor(QPalette.Window, QColor(240, 240, 240))
        palette.setColor(QPalette.WindowText, QColor(0, 0, 0))
        palette.setColor(QPalette.Base, QColor(255, 255, 255))
        palette.setColor(QPalette.AlternateBase, QColor(240, 240, 240))
        palette.setColor(QPalette.ToolTipBase, QColor(255, 255, 220))
        palette.setColor(QPalette.ToolTipText, QColor(0, 0, 0))
        palette.setColor(QPalette.Text, QColor(0, 0, 0))
        palette.setColor(QPalette.Button, QColor(240, 240, 240))
        palette.setColor(QPalette.ButtonText, QColor(0, 0, 0))
        palette.setColor(QPalette.BrightText, QColor(255, 0, 0))
        palette.setColor(QPalette.Highlight, QColor(0, 120, 215))
        palette.setColor(QPalette.HighlightedText, QColor(255, 255, 255))
        app.setPalette(palette)
        
        font = QFont("Segoe UI", 9)
        app.setFont(font)

class StyledButton(QPushButton):
    def __init__(self, text, parent=None):
        super().__init__(text, parent)
        self.setMinimumHeight(28)
        self.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        self.setStyleSheet("""
        QPushButton {
            background-color: #f0f0f0;
            border: 1px solid #d0d0d0;
            border-radius: 4px;
            padding: 5px 12px;
            min-width: 80px;
        }
        QPushButton:hover {
            background-color: #e0e0e0;
        }
        QPushButton:pressed {
            background-color: #d0d0d0;
        }
        QPushButton:disabled {
            background-color: #f8f8f8;
            color: #a0a0a0;
        }
        """)

class PrimaryButton(StyledButton):
    def __init__(self, text, parent=None):
        super().__init__(text, parent)
        self.setStyleSheet("""
        QPushButton {
            background-color: #0078d7;
            color: white;
            border: 1px solid #005fa3;
            border-radius: 4px;
            padding: 5px 12px;
            min-width: 80px;
        }
        QPushButton:hover {
            background-color: #0066b4;
        }
        QPushButton:pressed {
            background-color: #005fa3;
        }
        QPushButton:disabled {
            background-color: #a0c6e8;
            color: #e0e0e0;
        }
        """)

class StyledLineEdit(QLineEdit):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setMinimumHeight(28)
        self.setStyleSheet("""
        QLineEdit {
            border: 1px solid #d0d0d0;
            border-radius: 4px;
            padding: 3px 8px;
        }
        QLineEdit:focus {
            border: 1px solid #0078d7;
        }
        """)

class StyledComboBox(QComboBox):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setMinimumHeight(28)
        self.setStyleSheet("""
        QComboBox {
            border: 1px solid #d0d0d0;
            border-radius: 4px;
            padding: 3px 8px;
        }
        QComboBox:focus {
            border: 1px solid #0078d7;
        }
        QComboBox::drop-down {
            subcontrol-origin: padding;
            subcontrol-position: top right;
            width: 20px;
            border-left-width: 1px;
            border-left-color: #d0d0d0;
            border-left-style: solid;
            border-top-right-radius: 4px;
            border-bottom-right-radius: 4px;
        }
        """)

class StyledDateEdit(QDateEdit):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setMinimumHeight(28)
        self.setCalendarPopup(True)
        self.setDate(QDate.currentDate())
        self.setStyleSheet("""
        QDateEdit {
            border: 1px solid #d0d0d0;
            border-radius: 4px;
            padding: 3px 8px;
        }
        QDateEdit:focus {
            border: 1px solid #0078d7;
        }
        QDateEdit::drop-down {
            subcontrol-origin: padding;
            subcontrol-position: top right;
            width: 20px;
            border-left-width: 1px;
            border-left-color: #d0d0d0;
            border-left-style: solid;
            border-top-right-radius: 4px;
            border-bottom-right-radius: 4px;
        }
        """)
        
class StyledTableWidget(QTableWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setStyleSheet("""
        QTableWidget {
            border: 1px solid #d0d0d0;
            border-radius: 4px;
            gridline-color: #e0e0e0;
        }
        QHeaderView::section {
            background-color: #f8f8f8;
            padding: 5px;
            border: 1px solid #e0e0e0;
        }
        QTableWidget::item {
            padding: 5px;
        }
        QTableWidget::item:selected {
            background-color: #0078d7;
            color: white;
        }
        QScrollBar:vertical {
            border: none;
            background: #f0f0f0;
            width: 12px;
            margin: 0px 0px 0px 0px;
        }
        QScrollBar::handle:vertical {
            background: #c0c0c0;
            min-height: 20px;
            border-radius: 6px;
        }
        QScrollBar::add-line:vertical {
            border: none;
            background: none;
            height: 0px;
            subcontrol-position: bottom;
            subcontrol-origin: margin;
        }
        QScrollBar::sub-line:vertical {
            border: none;
            background: none;
            height: 0px;
            subcontrol-position: top;
            subcontrol-origin: margin;
        }
        QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {
            background: none;
        }
        QScrollBar::handle:vertical:hover {
            background: #a0a0a0;
        }
        QScrollBar::handle:vertical:pressed {
            background: #808080;
        }
        """)
        self.setAlternatingRowColors(True)
        self.setSelectionBehavior(QTableWidget.SelectRows)
        self.setSelectionMode(QTableWidget.SingleSelection)
        self.verticalHeader().setVisible(False)
        self.setVerticalScrollMode(QTableWidget.ScrollPerPixel)
        self.setHorizontalScrollMode(QTableWidget.ScrollPerPixel)
        self.verticalHeader().setDefaultSectionSize(24)

class StyledGroupBox(QGroupBox):
    def __init__(self, title="", parent=None):
        super().__init__(title, parent)
        self.setStyleSheet("""
        QGroupBox {
            border: 1px solid #d0d0d0;
            border-radius: 4px;
            margin-top: 10px;
            padding-top: 15px;
        }
        QGroupBox::title {
            subcontrol-origin: margin;
            left: 10px;
            padding: 0 5px;
        }
        """)

class OfficeSuppliesSystem(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("办公文具管理系统")
        self.setGeometry(100, 100, 1100, 750)
        # 检查图标文件是否存在
        icon_path = "office_supplies.png"
        if os.path.exists(icon_path):
            self.setWindowIcon(QIcon(icon_path))
        
        # 初始化数据库
        self.init_db()
        
        # 创建主窗口部件
        self.main_widget = QWidget()
        self.setCentralWidget(self.main_widget)
        
        # 创建主布局
        self.main_layout = QVBoxLayout()
        self.main_widget.setLayout(self.main_layout)
        
        # 创建标题栏
        self.create_header()
        
        # 创建标签页
        self.tabs = QTabWidget()
        self.tabs.setStyleSheet("""
        QTabWidget::pane {
            border: 1px solid #d0d0d0;
            border-radius: 4px;
            margin-top: 5px;
        }
        QTabBar::tab {
            background: #f0f0f0;
            border: 1px solid #d0d0d0;
            border-bottom: none;
            border-top-left-radius: 4px;
            border-top-right-radius: 4px;
            padding: 5px 15px;
            margin-right: 2px;
        }
        QTabBar::tab:selected {
            background: white;
            border-bottom: 1px solid white;
            margin-bottom: -1px;
        }
        QTabBar::tab:hover {
            background: #e0e0e0;
        }
        """)
        self.main_layout.addWidget(self.tabs)
        
        # 添加各个功能标签页
        self.create_supplies_tab()      # 文具基础资料
        self.create_purchase_tab()      # 文具采购
        self.create_usage_tab()         # 文具领用
        self.create_inventory_tab()     # 文具库存
        self.create_reports_tab()       # 文件报表
        
        # 加载初始数据
        self.load_supplies()
        self.load_purchases()
        self.load_usages()
        self.load_inventory()
    
    def create_header(self):
        """创建标题栏"""
        header = QWidget()
        header.setStyleSheet("background-color: #0078d7; color: white;")
        header_layout = QHBoxLayout(header)
        header_layout.setContentsMargins(15, 10, 15, 10)
        
        title = QLabel("办公文具管理系统")
        title.setStyleSheet("font-size: 16px; font-weight: bold;")
        
        header_layout.addWidget(title)
        header_layout.addStretch()
        
        # 添加当前日期
        date_label = QLabel(datetime.now().strftime("%Y-%m-%d"))
        date_label.setStyleSheet("font-size: 12px;")
        header_layout.addWidget(date_label)
        
        self.main_layout.addWidget(header)
    
    def init_db(self):
        """初始化数据库"""
        self.conn = sqlite3.connect("office_supplies.db")
        self.cursor = self.conn.cursor()
        
        # 创建文具基础资料表
        self.cursor.execute("""
        CREATE TABLE IF NOT EXISTS supplies (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            name TEXT NOT NULL,
            category TEXT NOT NULL,
            specification TEXT,
            unit TEXT NOT NULL,
            min_stock INTEGER DEFAULT 0,
            remark TEXT
        )
        """)
        
        # 创建采购记录表
        self.cursor.execute("""
        CREATE TABLE IF NOT EXISTS purchases (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            supply_id INTEGER NOT NULL,
            supplier TEXT NOT NULL,
            purchase_date TEXT NOT NULL,
            quantity INTEGER NOT NULL,
            price REAL NOT NULL,
            amount REAL NOT NULL,
            purchaser TEXT NOT NULL,
            remark TEXT,
            FOREIGN KEY (supply_id) REFERENCES supplies (id)
        )
        """)
        
        # 创建领用记录表
        self.cursor.execute("""
        CREATE TABLE IF NOT EXISTS usages (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            supply_id INTEGER NOT NULL,
            user_name TEXT NOT NULL,
            department TEXT NOT NULL,
            usage_date TEXT NOT NULL,
            quantity INTEGER NOT NULL,
            purpose TEXT,
            remark TEXT,
            FOREIGN KEY (supply_id) REFERENCES supplies (id)
        )
        """)
        
        # 创建库存表
        self.cursor.execute("""
        CREATE TABLE IF NOT EXISTS inventory (
            supply_id INTEGER PRIMARY KEY,
            quantity INTEGER NOT NULL,
            last_update TEXT NOT NULL,
            FOREIGN KEY (supply_id) REFERENCES supplies (id)
        )
        """)
        
        self.conn.commit()
    
    def create_form_group(self, title, left_form, right_form):
        """创建表单组"""
        form_group = StyledGroupBox(title)
        form_layout = QHBoxLayout()
        form_group.setLayout(form_layout)
        form_layout.addLayout(left_form)
        form_layout.addLayout(right_form)
        return form_group
    
    def create_supplies_tab(self):
        """创建文具基础资料标签页"""
        self.supplies_tab = QWidget()
        self.tabs.addTab(self.supplies_tab, "基础资料")
        
        # 主布局 - 使用水平布局
        main_layout = QHBoxLayout()
        main_layout.setContentsMargins(10, 10, 10, 10)
        main_layout.setSpacing(15)
        self.supplies_tab.setLayout(main_layout)
        
        # 左侧表单区域 (1/3宽度)
        left_widget = QWidget()
        left_widget.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding)
        left_layout = QVBoxLayout()
        left_widget.setLayout(left_layout)
        main_layout.addWidget(left_widget, stretch=1)  # 设置stretch为1
        
        # 表单组
        form_group = StyledGroupBox("文具信息")
        left_layout.addWidget(form_group)
        
        form_layout = QFormLayout()
        form_layout.setSpacing(10)
        form_layout.setContentsMargins(15, 15, 15, 15)
        form_group.setLayout(form_layout)
        
        self.supply_name_input = StyledLineEdit()
        form_layout.addRow(QLabel("文具名称:"), self.supply_name_input)
        
        self.supply_category_combo = StyledLineEdit()
        # self.supply_category_combo.addItems(["笔类", "纸类", "文件夹", "办公设备", "其他"])
        form_layout.addRow(QLabel("文具类别:"), self.supply_category_combo)
        
        self.supply_spec_input = StyledLineEdit()
        form_layout.addRow(QLabel("规格型号:"), self.supply_spec_input)
        
        self.supply_unit_combo = StyledLineEdit()
        # self.supply_unit_combo.addItems(["支", "本", "个", "盒", "包", "台"])
        form_layout.addRow(QLabel("单位:"), self.supply_unit_combo)
        
        self.supply_min_stock_input = StyledLineEdit()
        self.supply_min_stock_input.setText("0")
        form_layout.addRow(QLabel("最低库存:"), self.supply_min_stock_input)
        
        self.supply_remark_input = StyledLineEdit()
        form_layout.addRow(QLabel("备注:"), self.supply_remark_input)
        
        # 按钮布局
        button_layout = QHBoxLayout()
        button_layout.setSpacing(10)
        
        self.add_supply_btn = PrimaryButton("添加文具")
        self.add_supply_btn.setIcon(QIcon.fromTheme("list-add"))
        self.add_supply_btn.clicked.connect(self.add_supply)
        button_layout.addWidget(self.add_supply_btn)
        
        self.update_supply_btn = StyledButton("更新文具")
        self.update_supply_btn.setIcon(QIcon.fromTheme("document-save"))
        self.update_supply_btn.clicked.connect(self.update_supply)
        button_layout.addWidget(self.update_supply_btn)
        
        self.delete_supply_btn = StyledButton("删除文具")
        self.delete_supply_btn.setIcon(QIcon.fromTheme("edit-delete"))
        self.delete_supply_btn.clicked.connect(self.delete_supply)
        button_layout.addWidget(self.delete_supply_btn)
        
        left_layout.addLayout(button_layout)
        left_layout.addStretch()  # 添加弹性空间使表单保持在顶部
        
        # 右侧表格区域 (2/3宽度)
        right_widget = QWidget()
        right_widget.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        right_layout = QVBoxLayout()
        right_widget.setLayout(right_layout)
        main_layout.addWidget(right_widget, stretch=2)  # 设置stretch为2
        
        # 文具表格
        table_group = StyledGroupBox("文具列表")
        right_layout.addWidget(table_group)
        
        table_layout = QVBoxLayout()
        table_group.setLayout(table_layout)
        
        self.supplies_table = StyledTableWidget()
        self.supplies_table.setColumnCount(7)
        self.supplies_table.setHorizontalHeaderLabels(["ID", "文具名称", "类别", "规格型号", "单位", "最低库存", "备注"])
        self.supplies_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        # 设置列宽调整方式
        header = self.supplies_table.horizontalHeader()
        header.setSectionResizeMode(QHeaderView.ResizeToContents)  # 根据内容调整宽度
        header.setSectionResizeMode(1, QHeaderView.Stretch)  # 让名称列可以拉伸
        header.setStretchLastSection(True)  # 让最后一列填满剩余空间
        
        self.supplies_table.cellClicked.connect(self.populate_supply_fields)
        table_layout.addWidget(self.supplies_table)
    
    def create_purchase_tab(self):
        """创建文具采购标签页"""
        self.purchase_tab = QWidget()
        self.tabs.addTab(self.purchase_tab, "文具采购")
        
        # 主布局 - 使用水平布局
        main_layout = QHBoxLayout()
        main_layout.setContentsMargins(10, 10, 10, 10)
        main_layout.setSpacing(15)
        self.purchase_tab.setLayout(main_layout)
        
        # 左侧表单区域 (1/3宽度)
        left_widget = QWidget()
        left_widget.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding)
        left_layout = QVBoxLayout()
        left_widget.setLayout(left_layout)
        main_layout.addWidget(left_widget, stretch=1)  # 设置stretch为1
        
        # 表单组
        form_group = StyledGroupBox("采购信息")
        left_layout.addWidget(form_group)
        
        form_layout = QFormLayout()
        form_layout.setSpacing(10)
        form_layout.setContentsMargins(15, 15, 15, 15)
        form_group.setLayout(form_layout)
        
        self.purchase_supply_combo = StyledComboBox()
        form_layout.addRow(QLabel("文具名称:"), self.purchase_supply_combo)
        
        self.purchase_supplier_input = StyledLineEdit()
        form_layout.addRow(QLabel("供应商:"), self.purchase_supplier_input)
        
        self.purchase_purchaser_input = StyledLineEdit()
        form_layout.addRow(QLabel("采购人:"), self.purchase_purchaser_input)
        
        self.purchase_date_input = StyledDateEdit()
        form_layout.addRow(QLabel("采购日期:"), self.purchase_date_input)
        
        self.purchase_quantity_input = StyledLineEdit()
        form_layout.addRow(QLabel("数量:"), self.purchase_quantity_input)
        
        self.purchase_price_input = StyledLineEdit()
        form_layout.addRow(QLabel("单价:"), self.purchase_price_input)
        
        # 按钮布局
        button_layout = QHBoxLayout()
        button_layout.setSpacing(10)
        
        self.add_purchase_btn = PrimaryButton("添加采购")
        self.add_purchase_btn.setIcon(QIcon.fromTheme("list-add"))
        self.add_purchase_btn.clicked.connect(self.add_purchase)
        button_layout.addWidget(self.add_purchase_btn)
        
        button_layout.addStretch()
        left_layout.addLayout(button_layout)
        left_layout.addStretch()  # 添加弹性空间使表单保持在顶部
        
        # 右侧表格区域 (2/3宽度)
        right_widget = QWidget()
        right_widget.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        right_layout = QVBoxLayout()
        right_widget.setLayout(right_layout)
        main_layout.addWidget(right_widget, stretch=2)  # 设置stretch为2
        
        # 采购记录表格
        table_group = StyledGroupBox("采购记录")
        right_layout.addWidget(table_group)
        
        table_layout = QVBoxLayout()
        table_group.setLayout(table_layout)
        
        self.purchases_table = StyledTableWidget()
        self.purchases_table.setColumnCount(8)
        self.purchases_table.setHorizontalHeaderLabels(["ID", "文具名称", "供应商", "采购日期", "数量", "单价", "金额", "采购人"])
        self.purchases_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.purchases_table.cellClicked.connect(self.populate_purchase_fields)
        table_layout.addWidget(self.purchases_table)

    def create_usage_tab(self):
        """创建文具领用标签页"""
        self.usage_tab = QWidget()
        self.tabs.addTab(self.usage_tab, "文具领用")
        
        # 主布局 - 使用水平布局
        main_layout = QHBoxLayout()
        main_layout.setContentsMargins(10, 10, 10, 10)
        main_layout.setSpacing(15)
        self.usage_tab.setLayout(main_layout)
        
        # 左侧表单区域 (1/3宽度)
        left_widget = QWidget()
        left_widget.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding)
        left_layout = QVBoxLayout()
        left_widget.setLayout(left_layout)
        main_layout.addWidget(left_widget, stretch=1)  # 设置stretch为1
        
        # 表单组
        form_group = StyledGroupBox("领用信息")
        left_layout.addWidget(form_group)
        
        form_layout = QFormLayout()
        form_layout.setSpacing(10)
        form_layout.setContentsMargins(15, 15, 15, 15)
        form_group.setLayout(form_layout)
        
        self.usage_supply_combo = StyledComboBox()
        form_layout.addRow(QLabel("文具名称:"), self.usage_supply_combo)
        
        self.usage_user_input = StyledLineEdit()
        form_layout.addRow(QLabel("领用人:"), self.usage_user_input)
        
        self.usage_department_combo = StyledComboBox()
        self.usage_department_combo.addItems(["行政部", "财务部", "人事部", "技术部", "市场部", "销售部"])
        form_layout.addRow(QLabel("部门:"), self.usage_department_combo)
        
        self.usage_date_input = StyledDateEdit()
        form_layout.addRow(QLabel("领用日期:"), self.usage_date_input)
        
        self.usage_quantity_input = StyledLineEdit()
        form_layout.addRow(QLabel("数量:"), self.usage_quantity_input)
        
        self.usage_purpose_input = StyledLineEdit()
        form_layout.addRow(QLabel("用途:"), self.usage_purpose_input)
        
        # 按钮布局
        button_layout = QHBoxLayout()
        button_layout.setSpacing(10)
        
        self.add_usage_btn = PrimaryButton("添加领用")
        self.add_usage_btn.setIcon(QIcon.fromTheme("list-add"))
        self.add_usage_btn.clicked.connect(self.add_usage)
        button_layout.addWidget(self.add_usage_btn)
        
        button_layout.addStretch()
        left_layout.addLayout(button_layout)
        left_layout.addStretch()  # 添加弹性空间使表单保持在顶部
        
        # 右侧表格区域 (2/3宽度)
        right_widget = QWidget()
        right_widget.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        right_layout = QVBoxLayout()
        right_widget.setLayout(right_layout)
        main_layout.addWidget(right_widget, stretch=2)  # 设置stretch为2
        
        # 领用记录表格
        table_group = StyledGroupBox("领用记录")
        right_layout.addWidget(table_group)
        
        table_layout = QVBoxLayout()
        table_group.setLayout(table_layout)
        
        self.usages_table = StyledTableWidget()
        self.usages_table.setColumnCount(7)
        self.usages_table.setHorizontalHeaderLabels(["ID", "文具名称", "领用人", "部门", "领用日期", "数量", "用途"])
        self.usages_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.usages_table.cellClicked.connect(self.populate_usage_fields)
        table_layout.addWidget(self.usages_table)
    
    def create_inventory_tab(self):
        """创建文具库存标签页"""
        self.inventory_tab = QWidget()
        self.tabs.addTab(self.inventory_tab, "文具库存")
        
        # 主布局
        layout = QVBoxLayout()
        layout.setContentsMargins(10, 10, 10, 10)
        layout.setSpacing(15)
        self.inventory_tab.setLayout(layout)
        
        # 搜索栏
        search_group = StyledGroupBox("库存查询")
        layout.addWidget(search_group)
        
        search_layout = QHBoxLayout()
        search_layout.setContentsMargins(15, 15, 15, 15)
        search_group.setLayout(search_layout)
        
        self.inventory_search_input = StyledLineEdit()
        self.inventory_search_input.setPlaceholderText("输入文具名称或类别")
        search_layout.addWidget(self.inventory_search_input)
        
        self.inventory_search_btn = PrimaryButton("搜索")
        self.inventory_search_btn.setIcon(QIcon.fromTheme("system-search"))
        self.inventory_search_btn.clicked.connect(self.search_inventory)
        search_layout.addWidget(self.inventory_search_btn)
        
        # 库存表格
        table_group = StyledGroupBox("库存列表")
        layout.addWidget(table_group)
        
        table_layout = QVBoxLayout()
        table_group.setLayout(table_layout)
        
        self.inventory_table = StyledTableWidget()
        self.inventory_table.setColumnCount(7)
        self.inventory_table.setHorizontalHeaderLabels(["文具ID", "文具名称", "类别", "规格型号", "单位", "库存数量", "最后更新"])
        self.inventory_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        table_layout.addWidget(self.inventory_table)
        
        # 库存预警
        warning_group = StyledGroupBox("库存预警")
        layout.addWidget(warning_group)
        
        warning_layout = QVBoxLayout()
        warning_group.setLayout(warning_layout)
        
        self.warning_table = StyledTableWidget()
        self.warning_table.setColumnCount(7)
        self.warning_table.setHorizontalHeaderLabels(["文具ID", "文具名称", "类别", "单位", "当前库存", "最低库存", "状态"])
        self.warning_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        warning_layout.addWidget(self.warning_table)
    
    def create_reports_tab(self):
        """创建文件报表标签页"""
        self.reports_tab = QWidget()
        self.tabs.addTab(self.reports_tab, "文件报表")
        
        # 主布局
        layout = QVBoxLayout()
        layout.setContentsMargins(10, 10, 10, 10)
        layout.setSpacing(15)
        self.reports_tab.setLayout(layout)
        
        # 报表选项
        options_group = StyledGroupBox("报表选项")
        layout.addWidget(options_group)
        
        options_layout = QHBoxLayout()
        options_layout.setContentsMargins(15, 15, 15, 15)
        options_group.setLayout(options_layout)
        
        self.report_type_combo = StyledComboBox()
        self.report_type_combo.addItems(["采购汇总", "领用汇总", "库存报表", "库存预警"])
        options_layout.addWidget(self.report_type_combo)
        
        self.start_date_input = StyledDateEdit()
        self.start_date_input.setDisplayFormat("yyyy-MM-dd")
        options_layout.addWidget(QLabel("开始日期:"))
        options_layout.addWidget(self.start_date_input)
        
        self.end_date_input = StyledDateEdit()
        self.end_date_input.setDisplayFormat("yyyy-MM-dd")
        options_layout.addWidget(QLabel("结束日期:"))
        options_layout.addWidget(self.end_date_input)
        
        self.generate_report_btn = PrimaryButton("生成报表")
        self.generate_report_btn.setIcon(QIcon.fromTheme("document-export"))
        self.generate_report_btn.clicked.connect(self.generate_report)
        options_layout.addWidget(self.generate_report_btn)
        
        # 报表表格
        table_group = StyledGroupBox("报表结果")
        layout.addWidget(table_group)
        
        table_layout = QVBoxLayout()
        table_group.setLayout(table_layout)
        
        self.report_table = StyledTableWidget()
        table_layout.addWidget(self.report_table)
        
        # 导出按钮
        export_layout = QHBoxLayout()
        export_layout.addStretch()
        
        self.export_excel_btn = StyledButton("导出Excel")
        self.export_excel_btn.setIcon(QIcon.fromTheme("x-office-spreadsheet"))
        self.export_excel_btn.clicked.connect(self.export_to_excel)
        export_layout.addWidget(self.export_excel_btn)
        
        # self.export_pdf_btn = StyledButton("导出PDF")
        # self.export_pdf_btn.setIcon(QIcon.fromTheme("application-pdf"))
        # self.export_pdf_btn.clicked.connect(self.export_to_pdf)
        # export_layout.addWidget(self.export_pdf_btn)
        
        layout.addLayout(export_layout)
    
    # 数据加载方法
    def load_supplies(self):
        """加载文具基础资料"""
        self.cursor.execute("SELECT id, name, category, specification, unit, min_stock, remark FROM supplies")
        supplies = self.cursor.fetchall()
        
        self.supplies_table.setRowCount(len(supplies))
        for row, supply in enumerate(supplies):
            for col, data in enumerate(supply):
                self.supplies_table.setItem(row, col, QTableWidgetItem(str(data)))
        
        # 更新采购和领用页面的文具下拉框
        self.purchase_supply_combo.clear()
        self.usage_supply_combo.clear()
        self.cursor.execute("SELECT id, name FROM supplies")
        all_supplies = self.cursor.fetchall()
        for supply in all_supplies:
            self.purchase_supply_combo.addItem(f"{supply[0]} - {supply[1]}", supply[0])
            self.usage_supply_combo.addItem(f"{supply[0]} - {supply[1]}", supply[0])
    
    def load_purchases(self):
        """加载采购记录"""
        self.cursor.execute("""
        SELECT p.id, s.name, p.supplier, p.purchase_date, p.quantity, p.price, p.amount, p.purchaser
        FROM purchases p
        JOIN supplies s ON p.supply_id = s.id
        ORDER BY p.purchase_date DESC
        """)
        purchases = self.cursor.fetchall()
        
        self.purchases_table.setRowCount(len(purchases))
        for row, purchase in enumerate(purchases):
            for col, data in enumerate(purchase):
                self.purchases_table.setItem(row, col, QTableWidgetItem(str(data)))
    
    def load_usages(self):
        """加载领用记录"""
        self.cursor.execute("""
        SELECT u.id, s.name, u.user_name, u.department, u.usage_date, u.quantity, u.purpose
        FROM usages u
        JOIN supplies s ON u.supply_id = s.id
        ORDER BY u.usage_date DESC
        """)
        usages = self.cursor.fetchall()
        
        self.usages_table.setRowCount(len(usages))
        for row, usage in enumerate(usages):
            for col, data in enumerate(usage):
                self.usages_table.setItem(row, col, QTableWidgetItem(str(data)))
    
    def load_inventory(self):
        """加载库存数据"""
        self.cursor.execute("""
        SELECT i.supply_id, s.name, s.category, s.specification, s.unit, i.quantity, i.last_update
FROM inventory i
JOIN supplies s ON i.supply_id = s.id
WHERE i.quantity >= 1
ORDER BY i.quantity
        """)
        inventory = self.cursor.fetchall()
        
        self.inventory_table.setRowCount(len(inventory))
        for row, item in enumerate(inventory):
            for col, data in enumerate(item):
                self.inventory_table.setItem(row, col, QTableWidgetItem(str(data)))
        
        # 加载库存预警数据
        self.cursor.execute("""
        SELECT i.supply_id, s.name, s.category, s.unit, i.quantity, s.min_stock,
               CASE WHEN i.quantity <= s.min_stock THEN '不足' ELSE '充足' END
        FROM inventory i
        JOIN supplies s ON i.supply_id = s.id
        WHERE s.min_stock > 0
        ORDER BY i.quantity
        """)
        warnings = self.cursor.fetchall()
        
        self.warning_table.setRowCount(len(warnings))
        for row, warning in enumerate(warnings):
            for col, data in enumerate(warning):
                item = QTableWidgetItem(str(data))
                if col == 6 and data == "不足":
                    item.setForeground(QColor(255, 0, 0))  # 设置为红色
                self.warning_table.setItem(row, col, item)
    
    # 数据操作方法
    def add_supply(self):
        """添加文具"""
        name = self.supply_name_input.text().strip()
        category = self.supply_category_combo.text().strip()
        specification = self.supply_spec_input.text().strip()
        unit = self.supply_unit_combo.text().strip()
        min_stock = self.supply_min_stock_input.text().strip()
        remark = self.supply_remark_input.text().strip()
        
        if not name or not category or not unit:
            QMessageBox.warning(self, "警告", "请填写必填字段！")
            return
        
        # 检查文具名称是否已存在
        self.cursor.execute("SELECT COUNT(*) FROM supplies WHERE name=?", (name,))
        if self.cursor.fetchone()[0] > 0:
            QMessageBox.warning(self, "警告", "该文具名称已存在，请使用不同的名称！")
            return
        
        try:
            min_stock = int(min_stock) if min_stock else 0
        except ValueError:
            QMessageBox.warning(self, "警告", "最低库存必须是整数！")
            return
        
        try:
            self.cursor.execute(
                "INSERT INTO supplies (name, category, specification, unit, min_stock, remark) VALUES (?, ?, ?, ?, ?, ?)",
                (name, category, specification, unit, min_stock, remark)
            )
            supply_id = self.cursor.lastrowid
            
            # 初始化库存
            self.cursor.execute(
                "INSERT INTO inventory (supply_id, quantity, last_update) VALUES (?, 0, ?)",
                (supply_id, datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
            )
            
            self.conn.commit()
            QMessageBox.information(self, "成功", "文具添加成功！")
            self.clear_supply_fields()
            self.load_supplies()
            self.load_inventory()
        except Exception as e:
            QMessageBox.warning(self, "错误", f"添加失败: {str(e)}")
    
    def update_supply(self):
        """更新文具"""
        selected_row = self.supplies_table.currentRow()
        if selected_row == -1:
            QMessageBox.warning(self, "警告", "请选择要更新的文具！")
            return
        
        supply_id = self.supplies_table.item(selected_row, 0).text()
        name = self.supply_name_input.text().strip()
        category = self.supply_category_combo.text().strip()
        specification = self.supply_spec_input.text().strip()
        unit = self.supply_unit_combo.text().strip()
        min_stock = self.supply_min_stock_input.text().strip()
        remark = self.supply_remark_input.text().strip()
        
        if not name or not category or not unit:
            QMessageBox.warning(self, "警告", "请填写必填字段！")
            return
        
        try:
            min_stock = int(min_stock) if min_stock else 0
        except ValueError:
            QMessageBox.warning(self, "警告", "最低库存必须是整数！")
            return
        
        try:
            self.cursor.execute(
                "UPDATE supplies SET name=?, category=?, specification=?, unit=?, min_stock=?, remark=? WHERE id=?",
                (name, category, specification, unit, min_stock,                remark, supply_id)
            )
            self.conn.commit()
            QMessageBox.information(self, "成功", "文具更新成功！")
            self.load_supplies()
            self.load_inventory()
        except Exception as e:
            QMessageBox.warning(self, "错误", f"更新失败: {str(e)}")

    def delete_supply(self):
        """删除文具"""
        selected_row = self.supplies_table.currentRow()
        if selected_row == -1:
            QMessageBox.warning(self, "警告", "请选择要删除的文具！")
            return

        supply_id = self.supplies_table.item(selected_row, 0).text()

        # 检查是否有库存
        self.cursor.execute("SELECT quantity FROM inventory WHERE supply_id=?", (supply_id,))
        quantity = self.cursor.fetchone()[0]

        if quantity > 0:
            QMessageBox.warning(self, "警告", "该文具仍有库存，无法删除！")
            return

        reply = QMessageBox.question(
            self, "确认", "确定要删除这个文具吗？",
            QMessageBox.Yes | QMessageBox.No, QMessageBox.No)

        if reply == QMessageBox.Yes:
            try:
                # 删除库存记录
                self.cursor.execute("DELETE FROM inventory WHERE supply_id=?", (supply_id,))
                # 删除文具记录
                self.cursor.execute("DELETE FROM supplies WHERE id=?", (supply_id,))
                self.conn.commit()
                QMessageBox.information(self, "成功", "文具删除成功！")
                self.clear_supply_fields()
                self.load_supplies()
                self.load_inventory()
            except Exception as e:
                QMessageBox.warning(self, "错误", f"删除失败: {str(e)}")

    def add_purchase(self):
        """添加采购记录"""
        if self.purchase_supply_combo.currentIndex() == -1:
            QMessageBox.warning(self, "警告", "请选择文具！")
            return

        supply_id = self.purchase_supply_combo.currentData()
        supplier = self.purchase_supplier_input.text().strip()
        purchase_date = self.purchase_date_input.date().toString("yyyy-MM-dd")
        quantity_str = self.purchase_quantity_input.text().strip()
        price_str = self.purchase_price_input.text().strip()
        purchaser = self.purchase_purchaser_input.text().strip()

        if not supplier or not quantity_str or not price_str or not purchaser:
            QMessageBox.warning(self, "警告", "请填写必填字段！")
            return

        try:
            quantity = int(quantity_str)
            price = float(price_str)
            if quantity <= 0 or price <= 0:
                raise ValueError
        except ValueError:
            QMessageBox.warning(self, "警告", "数量和单价必须是正数！")
            return

        amount = quantity * price

        try:
            # 添加采购记录
            self.cursor.execute(
                "INSERT INTO purchases (supply_id, supplier, purchase_date, quantity, price, amount, purchaser) VALUES (?, ?, ?, ?, ?, ?, ?)",
                (supply_id, supplier, purchase_date, quantity, price, amount, purchaser)
            )

            # 更新库存
            self.cursor.execute("""
            INSERT OR REPLACE INTO inventory (supply_id, quantity, last_update)
            VALUES (?, 
                   COALESCE((SELECT quantity FROM inventory WHERE supply_id=?), 0) + ?,
                   ?)
            """, (supply_id, supply_id, quantity, datetime.now().strftime("%Y-%m-%d %H:%M:%S")))

            self.conn.commit()
            QMessageBox.information(self, "成功", "采购记录添加成功！")
            self.clear_purchase_fields()
            self.load_purchases()
            self.load_inventory()
        except Exception as e:
            QMessageBox.warning(self, "错误", f"添加失败: {str(e)}")

    def add_usage(self):
        """添加领用记录"""
        if self.usage_supply_combo.currentIndex() == -1:
            QMessageBox.warning(self, "警告", "请选择文具！")
            return

        supply_id = self.usage_supply_combo.currentData()
        user_name = self.usage_user_input.text().strip()
        department = self.usage_department_combo.currentText()
        usage_date = self.usage_date_input.date().toString("yyyy-MM-dd")
        quantity_str = self.usage_quantity_input.text().strip()
        purpose = self.usage_purpose_input.text().strip()

        if not user_name or not department or not quantity_str:
            QMessageBox.warning(self, "警告", "请填写必填字段！")
            return

        try:
            quantity = int(quantity_str)
            if quantity <= 0:
                raise ValueError
        except ValueError:
            QMessageBox.warning(self, "警告", "数量必须是正整数！")
            return

        # 检查库存是否足够
        self.cursor.execute("SELECT quantity FROM inventory WHERE supply_id=?", (supply_id,))
        result = self.cursor.fetchone()

        if not result or result[0] < quantity:
            QMessageBox.warning(self, "警告", "库存不足！")
            return

        try:
            # 添加领用记录
            self.cursor.execute(
                "INSERT INTO usages (supply_id, user_name, department, usage_date, quantity, purpose) VALUES (?, ?, ?, ?, ?, ?)",
                (supply_id, user_name, department, usage_date, quantity, purpose)
            )

            # 更新库存
            self.cursor.execute("""
            UPDATE inventory 
            SET quantity = quantity - ?, 
                last_update = ?
            WHERE supply_id = ?
            """, (quantity, datetime.now().strftime("%Y-%m-%d %H:%M:%S"), supply_id))

            self.conn.commit()
            QMessageBox.information(self, "成功", "领用记录添加成功！")
            self.clear_usage_fields()
            self.load_usages()
            self.load_inventory()
        except Exception as e:
            QMessageBox.warning(self, "错误", f"添加失败: {str(e)}")

    def search_inventory(self):
        """搜索库存"""
        keyword = self.inventory_search_input.text().strip()
        if not keyword:
            self.load_inventory()
            return

        self.cursor.execute("""
        SELECT i.supply_id, s.name, s.category, s.specification, s.unit, i.quantity, i.last_update
        FROM inventory i
        JOIN supplies s ON i.supply_id = s.id
        WHERE s.name LIKE ? OR s.category LIKE ?
        ORDER BY i.quantity
        """, (f"%{keyword}%", f"%{keyword}%"))

        inventory = self.cursor.fetchall()

        self.inventory_table.setRowCount(len(inventory))
        for row, item in enumerate(inventory):
            for col, data in enumerate(item):
                self.inventory_table.setItem(row, col, QTableWidgetItem(str(data)))

    def generate_report(self):
        """生成报表"""
        report_type = self.report_type_combo.currentText()
        start_date = self.start_date_input.date().toString("yyyy-MM-dd")
        end_date = self.end_date_input.date().toString("yyyy-MM-dd")

        if report_type == "采购汇总":
            self.cursor.execute("""
            SELECT s.name, s.category, s.unit, 
                   SUM(p.quantity) as total_quantity, 
                   SUM(p.amount) as total_amount,
                   COUNT(p.id) as purchase_count
            FROM purchases p
            JOIN supplies s ON p.supply_id = s.id
            WHERE p.purchase_date BETWEEN ? AND ?
            GROUP BY s.name, s.category, s.unit
            ORDER BY total_amount DESC
            """, (start_date, end_date))

            results = self.cursor.fetchall()
            self.report_table.setColumnCount(6)
            self.report_table.setHorizontalHeaderLabels(["文具名称", "类别", "单位", "采购总量", "总金额", "采购次数"])

        elif report_type == "领用汇总":
            self.cursor.execute("""
            SELECT s.name, s.category, s.unit, 
                   SUM(u.quantity) as total_quantity,
                   COUNT(u.id) as usage_count
            FROM usages u
            JOIN supplies s ON u.supply_id = s.id
            WHERE u.usage_date BETWEEN ? AND ?
            GROUP BY s.name, s.category, s.unit
            ORDER BY total_quantity DESC
            """, (start_date, end_date))

            results = self.cursor.fetchall()
            self.report_table.setColumnCount(5)
            self.report_table.setHorizontalHeaderLabels(["文具名称", "类别", "单位", "领用总量", "领用次数"])

        elif report_type == "库存报表":
            self.cursor.execute("""
            SELECT s.name, s.category, s.specification, s.unit, 
                   i.quantity, s.min_stock,
                   CASE WHEN i.quantity <= s.min_stock THEN '不足' ELSE '充足' END as status
            FROM inventory i
            JOIN supplies s ON i.supply_id = s.id
            ORDER BY i.quantity
            """)

            results = self.cursor.fetchall()
            self.report_table.setColumnCount(7)
            self.report_table.setHorizontalHeaderLabels(["文具名称", "类别", "规格", "单位", "库存量", "最低库存", "状态"])

        elif report_type == "库存预警":
            self.cursor.execute("""
            SELECT s.name, s.category, s.unit, i.quantity, s.min_stock,
                   CASE WHEN i.quantity <= s.min_stock THEN '不足' ELSE '充足' END as status
            FROM inventory i
            JOIN supplies s ON i.supply_id = s.id
            WHERE s.min_stock > 0
            ORDER BY i.quantity
            """)

            results = self.cursor.fetchall()
            self.report_table.setColumnCount(6)
            self.report_table.setHorizontalHeaderLabels(["文具名称", "类别", "单位", "库存量", "最低库存", "状态"])

        self.report_table.setRowCount(len(results))
        for row, record in enumerate(results):
            for col, data in enumerate(record):
                item = QTableWidgetItem(str(data))
                if report_type in ["库存报表", "库存预警"] and col == 6 and data == "不足":
                    item.setForeground(QColor(255, 0, 0))
                self.report_table.setItem(row, col, item)

        self.report_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)

    def export_to_excel(self):
        """导出报表到 Excel"""
        report_type = self.report_type_combo.currentText()
        headers = [self.report_table.horizontalHeaderItem(i).text() for i in range(self.report_table.columnCount())]
        data = []
        for row in range(self.report_table.rowCount()):
            row_data = []
            for col in range(self.report_table.columnCount()):
                item = self.report_table.item(row, col)
                if item is not None:
                    row_data.append(item.text())
                else:
                    row_data.append('')
            data.append(row_data)

        wb = Workbook()
        ws = wb.active
        ws.append(headers)
        for row in data:
            ws.append(row)

        file_path = f'{report_type}_report.xlsx'
        wb.save(file_path)
        QMessageBox.information(self, "成功", f"报表已导出到 {file_path}")

    def export_to_pdf(self):
        """导出报表到 PDF"""
        report_type = self.report_type_combo.currentText()
        headers = [self.report_table.horizontalHeaderItem(i).text() for i in range(self.report_table.columnCount())]
        data = []
        for row in range(self.report_table.rowCount()):
            row_data = []
            for col in range(self.report_table.columnCount()):
                item = self.report_table.item(row, col)
                if item is not None:
                    row_data.append(item.text())
                else:
                    row_data.append('')
            data.append(row_data)

        file_path = f'{report_type}_report.pdf'
        c = canvas.Canvas(file_path, pagesize=letter)
        y = 750
        for header in headers:
            c.drawString(100, y, header)
            c.drawString(100 + 150, y, '|')
            y -= 20
        y = 750 - 30
        for row in data:
            for i, cell in enumerate(row):
                c.drawString(100 + i * 150, y, cell)
            y -= 20
        c.save()
        QMessageBox.information(self, "成功", f"报表已导出到 {file_path}")

    # 表单填充方法
    def populate_supply_fields(self, row):
        """填充文具表单字段"""
        self.supply_name_input.setText(self.supplies_table.item(row, 1).text())
        self.supply_category_combo.setText(self.supplies_table.item(row, 2).text())
        self.supply_spec_input.setText(self.supplies_table.item(row, 3).text())
        self.supply_unit_combo.setText(self.supplies_table.item(row, 4).text())
        self.supply_min_stock_input.setText(self.supplies_table.item(row, 5).text())
        self.supply_remark_input.setText(self.supplies_table.item(row, 6).text())

    def populate_purchase_fields(self, row):
        """填充采购表单字段"""
        supply_name = self.purchases_table.item(row, 1).text()
        supply_id = self.purchases_table.item(row, 0).text()
        self.purchase_supply_combo.setCurrentText(f"{supply_id} - {supply_name}")
        self.purchase_supplier_input.setText(self.purchases_table.item(row, 2).text())
        self.purchase_date_input.setDate(QDate.fromString(self.purchases_table.item(row, 3).text(), "yyyy-MM-dd"))
        self.purchase_quantity_input.setText(self.purchases_table.item(row, 4).text())
        self.purchase_price_input.setText(self.purchases_table.item(row, 5).text())
        self.purchase_purchaser_input.setText(self.purchases_table.item(row, 7).text())

    def populate_usage_fields(self, row):
        """填充领用表单字段"""
        supply_name = self.usages_table.item(row, 1).text()
        supply_id = self.usages_table.item(row, 0).text()
        self.usage_supply_combo.setCurrentText(f"{supply_id} - {supply_name}")
        self.usage_user_input.setText(self.usages_table.item(row, 2).text())
        self.usage_department_combo.setCurrentText(self.usages_table.item(row, 3).text())
        self.usage_date_input.setDate(QDate.fromString(self.usages_table.item(row, 4).text(), "yyyy-MM-dd"))
        self.usage_quantity_input.setText(self.usages_table.item(row, 5).text())
        self.usage_purpose_input.setText(self.usages_table.item(row, 6).text())

    # 表单清空方法
    def clear_supply_fields(self):
        """清空文具表单"""
        self.supply_name_input.clear()
        self.supply_category_combo.clear()
        self.supply_spec_input.clear()
        self.supply_unit_combo.clear()
        self.supply_min_stock_input.setText("0")
        self.supply_remark_input.clear()

    def clear_purchase_fields(self):
        """清空采购表单"""
        self.purchase_supplier_input.clear()
        self.purchase_quantity_input.clear()
        self.purchase_price_input.clear()
        self.purchase_purchaser_input.clear()
        self.purchase_date_input.setDate(QDate.currentDate())

    def clear_usage_fields(self):
        """清空领用表单"""
        self.usage_user_input.clear()
        self.usage_department_combo.setCurrentIndex(0)
        self.usage_quantity_input.clear()
        self.usage_purpose_input.clear()
        self.usage_date_input.setDate(QDate.currentDate())

    def closeEvent(self, event):
        """关闭窗口时关闭数据库连接"""
        self.conn.close()
        event.accept()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    DevExpressStyle.apply_style(app)
    window = OfficeSuppliesSystem()
    window.show()
    sys.exit(app.exec_())